import net from "net";
const events = require("events");
const EventEmitter = events.EventEmitter || events;
class Tcp_Client_Extension extends EventEmitter {
    tcp_client: net.Socket
    isConnected: boolean;
    host: string;
    port: number;
    interval: any;
    timeOut: any;
    isRcv: boolean;
    isSend: boolean;

    /**
     * 默认构造器
     * @param {number} host 
     * @param {boolean} port 
    */
    constructor(host: string, port: number) {
        super();
        this.host = host;
        this.port = port;
        this.isConnected = false;
        this.interval = null;
        this.timeOut = null;
        this.isSend = false;
        this.isRcv = false;
        this.config(host, port, true);

    }
    config(host: string, port: number, isFirst: boolean) {
        this.tcp_client = new net.Socket();
        this.tcp_client.setTimeout(600000);
        const modbus = this;
        console.log('connect to Server ....', host, port);
        // 连接 tcp server
        this.tcp_client.connect({ host: host, port: port }, function () {
            console.log('connected to Server');
            modbus.isConnected = true;
        })
        this.tcp_client.on('timeout', () => {
            console.log('=======================socket timeout===================');
            this.isConnected = false;
            this.tcp_client.end();
        });
        // 接收数据
        this.tcp_client.on('data', modbus.emit.bind(modbus, "data"))

        this.tcp_client.on('end', function () {
            // console.log('data end!');
            // modbus.isConnected = false;
        })

        this.tcp_client.on('error', function (err) {
            // modbus.isConnected = false;
            // console.log(err)
            // console.log('tcp_client error,reconnect ...!');
        })
        if (this.interval != null) {
            clearInterval(this.interval);
            this.interval = null;
        }
        this.interval = setInterval(() => {
            // console.log(modbus.isConnected)
            if (modbus.isConnected == false) {
                // clearInterval(this.interval);
                // this.interval = null;
                console.log(`\x1b[0;31m！！！！！！！！！！！！！！！！！！！！！！！！！！tcpzs【${this.host}:${this.port}】断线重连！！！！！！！！！！！！！！！！！！！！！！\x1b[0;37m`)
                // modbus.tcp_client.destroy()
                // modbus.config(host, port, false);
                modbus.tcp_client.connect({ host: modbus.host, port: modbus.port }, () => {
                    console.log('connected to Server');
                    modbus.isConnected = true;
                })
                modbus.tcp_client.setTimeout(600000);
            } else {
                // console.log(`\x1b[0;32m=================================${this.host}:${this.port}连接正常:${this.isConnected}====================================\x1b[0;37m`)
            }
        }, 3000);
    }
    setIsRcvOk() {
        this.isRcv = true;
    }
    tcpClientSendMsg(msg: Buffer) {
        this.isSend = true;
        if (this.isConnected) {
            console.log(`send CMD==============>`)
            this.tcp_client.write(msg);
            if (this.timeOut != null) {
                clearTimeout(this.timeOut);
                this.timeOut = null;
            }
            this.timeOut = setTimeout(() => {
                clearTimeout(this.timeOut);
                this.timeOut = null;
                if (this.isSend == true && this.isRcv == false) {
                    this.isConnected = false;
                }
                this.isSend = false;
                this.isRcv = false;
            }, 300)
        } else {
            console.log(`设备未连接`)
            this.isConnected = false;
        }
    }

}
export { Tcp_Client_Extension };
